﻿using System;
using System.Collections.Generic;
using System.Data;

using Gurucore.Framework.Core;
using Gurucore.Framework.DataAccess;
using Gurucore.Framework.DataAccess.Persistence;

namespace #class.Namespace#
{
	public sealed class #class.Name#_Transformer : DTOTransformer
	{
		public #class.Name#_Transformer()
		{
		}

		public override List<T> Transform<T>(System.Data.IDataReader p_reader, T p_sample)
		{
			List<T> arrDTO = new List<T>();
			List<string> arrColumn = new List<string>();
			for (int i = 0; i < p_reader.FieldCount; i++)
			{
				arrColumn.Add(p_reader.GetName(i));
			}

			TableInfoManager oTableInfoMgr = Application.GetInstance().GetGlobalSharedObject<TableInfoManager>();
			TableInfo oTableInfo = oTableInfoMgr.GetTableInfo(typeof(T));
			DataAccessContext oDACtx = DataAccessContext.GetDataAccessContext();
			string sTablePrefix = oTableInfo.UseTablePrefix ? oDACtx.GetTablePrefix() : string.Empty;
			
			int nReadRow = 0;
			while (p_reader.Read())
			{
				#class.Name#_Proxy oDTO = null;

				oDTO = new #class.Name#_Proxy();

				<ad:foreach collection="#class.Properties#" var="property">
				if (((arrColumn == null) || (arrColumn.Count == 0) || (arrColumn.Contains(sTablePrefix + "#property.FieldName#"))) && (p_reader[sTablePrefix + "#property.FieldName#"] != DBNull.Value))
				{
					oDTO._#property.Name# = (#property.Type#)Convert.ChangeType(p_reader[sTablePrefix + "#property.FieldName#"], typeof(#property.Type#));
					oDTO._#property.Name#State = DTOColumnState.Unchanged;
				}
				</ad:foreach>

				//arrDTO.Add((T)Convert.ChangeType(oDTO, typeof(T)));
				arrDTO.Add((T)((object)oDTO));
				nReadRow++;
			}
			return arrDTO;
		}
	}
}
